<?php


namespace App\EventListener;


use App\Entity\Setting;
use App\Utils\Helper\GeneralHelper;
use App\Utils\Helper\GetterHelper;
use App\Utils\Helper\ListenerHelper;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

class AuthFrontendListener {
    protected $event;

    public function onKernelController (ControllerEvent $event) {
        $this->event = $event;

        $this->main();
    }

    public function main () {
        // 校验是否是 Frontend Controller
        if (!$this->verifyControllerDomain()) {
            return;
        }

        // 校验是否为公共可访问action
        if ($this->isGlobalActions()) {
            return;
        }

        // 校验是否开启了维护模式
        if ($this->isMaintenance()) {
            header("Location: /common/maintenance");
            exit;
        }
    }

    /**
     * 校验是否是 Frontend Controller
     * @return bool
     */
    private function verifyControllerDomain (): bool {
        $result = false;

        $target_controller_domains = ['Frontend'];
        $_controller = $this->event->getRequest()->attributes->get('_controller');
        $controller_domain = ListenerHelper::getControllerDomain($_controller);
        $result = in_array($controller_domain, $target_controller_domains);

        return $result;
    }

    /**
     * 公共访问方法
     * @return bool
     */
    private function isGlobalActions (): bool {
        $result = false;

        $given_full_controller = $this->event->getRequest()->attributes->get('_controller');
        $public_full_controllers = [
            'App\Controller\Frontend\CommonController::maintenance',
        ];
        $result = in_array($given_full_controller, $public_full_controllers);

        return $result;
    }

    /**
     * 获取站点维护状态
     * @return mixed
     */
    private function isMaintenance () {
        return GetterHelper::getEntityManager()->getRepository(Setting::class)->getCurrentSetting()->getIsMaintenance();
    }
}